/*
 * 文件名： BccUtils.java
 * 
 * 创建日期： 2016年11月28日
 *
 * Copyright(C) 2016, by <a href="mailto:liws@xingyuanauto.com">liws</a>.
 *
 * 原始作者: liws
 *
 */
package com.moli.iov.protocol.util;

import java.util.Arrays;

import com.moli.iov.util.ByteArrayUtil;

/**
 * BCC异或校验 工具类
 *
 * @author <a href="mailto:liws@xingyuanauto.com">liws</a>
 *
 * @version $Revision$
 *
 * @since 2016年11月28日
 */
public class BccUtils {

	public static void main(String[] args) {
		byte[] bytes = bccBodyEncode(ByteArrayUtil.hexStringToBytes("232302FE4c4e425343423346334a5731383237363001017913050610002c0101030101400000163a0d42271058012e27100b00020101014d57a24ec3430d3e27100500071640c8017d479e0601250fdc01010fb401033c01013b070000000000000000000801010d42271000540001540fb40fb40fb40fb40fb40fb40fb40fb40fb40fb40fb40fb40fc80fc80fc80fc80fc80fc80fc80fc80fc80fc80fc80fc80fc80fc80fc80fc80fc80fc80fb40fc80fc80fc80fc80fc80fdc0fdc0fdc0fdc0fdc0fdc0fdc0fdc0fdc0fdc0fdc0fdc0fc80fc80fc80fc80fc80fc80fc80fc80fc80fc80fc80fc80fdc0fdc0fc80fc80fc80fdc0fc80fdc0fdc0fdc0fc80fdc0fc80fc80fc80fc80fc80fc80fc80fc80fc80fc80fc80fc8090101000e3b3b3c3b3c3b3b3b3b3b3b3b3b3ba000630002010014021d0000fe00018c000100000230001f0019111c0200470705c0de50dc9eca9d265405c12608032f4236050505c2554b27104443064205c3000000002903010405c406fa0c800000023905c5004001540e1d35ca05c60448002200000000"));
		System.out.println(ByteArrayUtil.toHexString(bytes));
		
	}
	
	/**
	 * 平台消息体 校验
	 * 
	 * @param bytes
	 * 
	 * @return
	 */
	public static byte[] bccBodyEncode(byte[] bytes) {

		if (bytes == null || bytes.length <= 0) {
			return bytes;
		}
		int length = bytes.length;
		// 校验完成且拼接校验码的字节序
		byte[] allBytes = new byte[length + 1];
		// bcc校验字节序 从命令标示(2)开始
		byte[] bccBytes = new byte[length - 2];
		System.arraycopy(bytes, 2, bccBytes, 0, length - 2);
		byte retByte = bccEncode(bccBytes);
		allBytes = Arrays.copyOf(bytes, length + 1);
		allBytes[length] = retByte;
		return allBytes;
	}

	/**
	 * bcc 异或校验返回byte
	 * 
	 * @param bytes
	 * 
	 * @return
	 */
	private static byte bccEncode(byte[] bytes) {
		byte retByte = 0;
		if (bytes == null || bytes.length <= 0) {
			return retByte;
		}
		retByte = bytes[0];
		for (int i = 1; i < bytes.length; i++) {
			retByte ^= bytes[i];
		}
		return retByte;
	}

	/**
	 * 包含消息在内的整个 报文体 校验BCC校验位是否正确
	 * 
	 * @param bytes
	 * 
	 * @return
	 */
	public static boolean checkBccCode(byte[] bytes) {

		if (bytes == null || bytes.length <= 0)
			return false;
		int length = bytes.length;
		//报文校验在byte[]中索引值
		int oldBccIndex = length - 1;
		// 待校验的字节数组 减去 "##"头2字节,bcc校验位尾部1字节
		//System.out.print("oldBytes="+ByteArrayUtil.toHexString(bytes));
		byte[] checkBytes = new byte[length - 1 - 2];
		//拷贝待校验的 byte[]字节序
		System.arraycopy(bytes, 2, checkBytes, 0, length - 1 - 2);
		//System.out.print("newBytes="+ByteArrayUtil.toHexString(checkBytes));
		// 原有数组校验位
		byte oldBccByte = bytes[oldBccIndex];
		// 新校验位
		byte newBccByte = bccEncode(checkBytes);

		if (oldBccByte == newBccByte)
			return true;
		return false;
	}
}
